package com.ryzx.common.filter;

import com.ryzx.common.util.RedisUtil;
import com.ryzx.common.util.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@Order(1)
@Component
public class SecurityFilter implements Filter {

    //忽略请求地址
    public List<String> ignoreUrl
            = Arrays.asList("/xxx","/xxx");

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String url = httpRequest.getRequestURI();
        if (ignoreUrl.contains(url)) {
            chain.doFilter(httpRequest, httpResponse);
        } else {
            String token = httpRequest.getHeader("token");
            String crossCall = httpRequest.getHeader("crossCall");
            if (!StringUtil.isBlank(token) && (RedisUtil.hasKey(token))) {
                //补充获取权限的代码
                chain.doFilter(httpRequest, httpResponse);
            }else if (!StringUtil.isBlank(crossCall) && (RedisUtil.hasKey(crossCall))) {
                chain.doFilter(httpRequest, httpResponse);
            }
            else{
                httpResponse.setStatus(404);
                httpResponse.setContentType("application/json; charset=UTF-8");
            }
        }
    }

    @Override
    public void destroy() {
    }
}